package chapter01;

/**
 * @ClassName BinarySearch
 * @Description: 有序数组中的二分查找
 * @Author: WangWenpeng
 * @date: 8:51 2021/8/29
 * @Version 1.0
 */
public class BinarySearch {

    public static void main(String[] args) {
        int index = binarySearch(new int[]{1, 3, 5, 7, 9, 11, 15}, 5);
        if (index == -1) {
            System.out.println("查找数据不存在");
        } else {
            System.out.println("index:" + index);
        }
    }

    /**
     * 有序数组中的二分查找
     */
    public static int binarySearch(int[] array, int target) {
        if (null == array || array.length == 0) {
            return -1;
        }

        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            int guess = array[mid];
            if (guess == target) {
                return mid;
            }
            if (guess > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }
}
